package com.dcits.weipt.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import com.dcits.weipt.service.Job;
import com.dcits.weipt.service.Job.ProgressThread;
import com.dcits.weipt.sharebin.DownLoadDataBin;

public class HelloDownload extends JFrame{

	private static final long serialVersionUID = 1L;
	private JPanel panel;
	private JLabel labelUrl;
	private JTextField textUrl;
	private JButton downLoadBtn;
	private int localWidth;
	private int localHeight;
	private JLabel labelAttention;
	private JLabel labelDir;
	private JLabel labelTitle;
	private JLabel labelSaveInfo;
	private JLabel labelFileName;
	private JFileChooser chooser;
	private JProgressBar processDown;
	private JDialog dialogInfo;
	private JLabel labelInfo;
	private DownLoadDataBin DD;
	private ProgressThread pt;
	private Job job;
	private JButton openFileBtn;

	/**
	 * 主窗体大小
	 */
	private static final int MAIN_WIDTH = 800;
	private static final int MAIN_HEIGHT = 600;
	
	private static final int INFO_POINT = 60;
	
	/**
	 * 弹出信息窗体*/
	private static final int INFO_WIDTH = 200;
	private static final int INFO_HEIGHT = 100;

	/**
	 * 字体大小
	 */
	private static final int TEXT_SIZE = 18;
	private static final int ACTUAL_TEXT_SIZE = 19;
	private static final int AREA_SIZE = 15;
	private static final int TEXTFIELD_HEIGHT = 25;
	private static final int TEXTFIELD_WIDTH = 200;
	private static final int BTN_WIDTH = 110;
	private static final String FONT_NAME = "微软雅黑";

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new HelloDownload();
	}
	
	public JProgressBar GetJprocessDown() {
		return processDown;
	}
	

	public HelloDownload() {
		// 获取电脑分辨率
		Toolkit toolkit = Toolkit.getDefaultToolkit();
		Dimension scrnsize = toolkit.getScreenSize();
		localWidth = scrnsize.width;
		localHeight = scrnsize.height;
		this.setTitle("Http下载工具        作者:weipt        email:weipt@dcits.com");
		this.setSize(MAIN_WIDTH, MAIN_HEIGHT);
		this.setLocation(localWidth / 2 - MAIN_WIDTH / 2, localHeight / 2 - MAIN_HEIGHT / 2);
		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // 当点击窗口的关闭按钮时退出程序（没有这一句，程序不会退出）
		this.setResizable(false); // 禁止客户改变窗体大小
		// 初始化子窗体
		this.setLayout(new BorderLayout());
		initServerInfoPanel();
		this.add(panel, null);
		this.setVisible(true);
		job = new Job(this);
		
	}

	/**
	 * 初始化panel窗体,服务端信息 将输入IP地址，端口，按钮放到一个jpanel中
	 */
	public void initServerInfoPanel() {
		panel = new JPanel();
		/**
		 * 标题标签
		 */
		labelTitle = new JLabel("Http  Download  Everything");
		labelTitle.setFont(new Font(FONT_NAME, Font.PLAIN,  TEXTFIELD_HEIGHT));

		/**
		 * url标签
		 */
		labelUrl = new JLabel("URL:");
		Font boldFont = (new Font(FONT_NAME, Font.BOLD, TEXT_SIZE));
		labelUrl.setFont(boldFont);

		/**
		 * url文本
		 */
		textUrl = new JTextField(12);
		textUrl.setFont(new Font(FONT_NAME, Font.PLAIN, TEXT_SIZE));
		
		/**
		 * 文件名称*/
		labelFileName = new JLabel("");
		labelFileName.setFont(boldFont);
		labelFileName.setForeground(Color.BLUE);
		

		/**
		 * 下载按钮
		 */
		downLoadBtn = new JButton("开始下载");
		downLoadBtn.setFont(boldFont);
		getRespCodeAction gca = new getRespCodeAction();
		downLoadBtn.addActionListener(gca);

		/**
		 * 选择器
		 */
		chooser = new JFileChooser();
		chooser.setVisible(true);
		
		/**
		 * 进度条*/
		processDown = new JProgressBar(0, 100);
		processDown.setBorderPainted(true);
		processDown.setBackground(new Color(255, 255, 255));
		processDown.setForeground(new Color(0, 100, 0));
		processDown.setStringPainted(true);
		
		
		openFileBtn = new JButton("打开文件目录");
		openFileBtn.setFont(boldFont);
		openFileBtn.addActionListener(new openFileAction());
		openFileBtn.setVisible(false);
		
		/**
		 * 隐藏域，用于存放下载路径
		 */
		labelDir = new JLabel("");
		labelDir.setVisible(false);

		/**
		 * 提示信息
		 */
		labelAttention = new JLabel("此软件只限神州数码内部下载文件使用");
		labelAttention.setFont(new Font(FONT_NAME, Font.BOLD, AREA_SIZE));
		labelAttention.setForeground(Color.BLUE);
		// 将元素加入jpanel中
		panel.setLayout(null);
		initBounds(); // 初始化坐标
		panel.add(labelUrl);
		panel.add(textUrl);
		panel.add(downLoadBtn);
		panel.add(labelAttention);
		panel.add(labelDir);
		panel.add(chooser);
		panel.add(processDown);
		panel.add(labelTitle);
		panel.add(labelFileName);
		panel.add(openFileBtn);
	}

	/**
	 * 初始化JPanel中元素坐标
	 */
	public void initBounds() {
		// 第一列初始化
		labelTitle.setBounds(240, 10, 600, 2 * ACTUAL_TEXT_SIZE);
		labelUrl.setBounds(0, INFO_POINT, 5 * TEXT_SIZE, ACTUAL_TEXT_SIZE);
		textUrl.setBounds(3 * TEXT_SIZE, INFO_POINT, 590, TEXTFIELD_HEIGHT);
		downLoadBtn.setBounds(580 + 5 * TEXT_SIZE, INFO_POINT, BTN_WIDTH, TEXTFIELD_HEIGHT);
		labelAttention.setBounds(250, 500, 5 * TEXTFIELD_WIDTH, 100);
		processDown.setBounds(200, 250, 400, 30);
		labelFileName.setBounds(150, 400, 500, 30);
		openFileBtn.setBounds(620, 250, 150, 30);
	}
	
	//Desktop.getDesktop().open(new File(chooseFileDir));   //打开windows资源管理
	
	/**
	 * 初始化提示信息窗口*/
    private void autoDialog(String msg){
		dialogInfo = new JDialog();
    	dialogInfo.setTitle("WARNING!!!");
    	labelInfo = new JLabel(msg);
    	dialogInfo.setBounds(localWidth/2-INFO_WIDTH/2, localHeight/2-INFO_HEIGHT/2, INFO_WIDTH, INFO_HEIGHT);
    	dialogInfo.add(labelInfo);
    	dialogInfo.setVisible(true);
	}
	
	/**
	 * 点击按钮，打开windows目录事件
	 */
	private class getRespCodeAction implements ActionListener,Runnable {
		@Override
		public void actionPerformed(ActionEvent arg0) {
			chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
			int returnVal = chooser.showSaveDialog(labelTitle);
			String chooseFileDir = chooser.getSelectedFile().toString();
			labelDir.setText(chooseFileDir);
			if (returnVal == JFileChooser.APPROVE_OPTION) {
				System.out.println("ready to download");
				getRespCodeAction ac = new getRespCodeAction();
				Thread t = new Thread(ac);
				t.start();
			} else {
				System.out.println("user cancle!");
			}
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				DD = DownLoadDataBin.getInstance();
				String normalUrl = textUrl.getText();
				if("".equals(normalUrl)) {
					autoDialog("please input url");
		        	return;
				}
				job.SetJobValue(normalUrl, labelDir.getText(), 1);
				boolean isFile = job.fetchFileMetaInfo();
				if(isFile) {
					openFileBtn.setVisible(true);
					labelFileName.setText(DD.getDownFileName());
					job.startJob();
					if("1".equals(DD.getDownFinishFlag())) {
						processDown.setForeground(new Color(124, 252, 0));
						processDown.setString(DD.getDownProcess());
					}
				}else {
					labelFileName.setText("无法找到要下载的文件，请检查网络或url");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private class openFileAction implements ActionListener{
		@Override
		public void actionPerformed(ActionEvent arg0) {
			try {
				Desktop.getDesktop().open(new File(labelDir.getText()));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}   //打开windows资源管理
		}
	}

}
